package com.jiamao.goplay.ui.user.vm;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

import com.jiamao.goplay.BR;
import com.jiamao.goplay.R;
import com.jiamao.goplay.bean.BaseRep;
import com.jiamao.goplay.bean.GoToWhereNumberItem;
import com.jiamao.goplay.bean.SearchAddrs;
import com.jiamao.goplay.bean.res.ResAddrDetail;
import com.jiamao.goplay.bean.res.ResMatch;
import com.jiamao.goplay.config.Config;
import com.jiamao.goplay.data.BaseSubscriber;
import com.jiamao.goplay.data.DataRepository;
import com.jiamao.goplay.ui.discover.MatchFragment;
import com.jiamao.goplay.ui.discover.SearchFragment;
import com.jiamao.goplay.ui.discover.vm.AddrDetailItemVM;
import com.jiamao.goplay.util.GsonUtil;
import com.tamsiree.rxkit.view.RxToast;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;

import java.io.Serializable;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.AppManager;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.base.MultiItemViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;
import me.tatarka.bindingcollectionadapter2.OnItemBind;

public class UserAddrDetailVM extends BaseViewModel<DataRepository> {

    private int page = 1;


    private int status;
    private String id;

    public ObservableField<String> imgUrl = new ObservableField<>("");
    public ObservableField<String> name = new ObservableField<>("");
    public ObservableField<String> addr = new ObservableField<>("");
    public ObservableField<String> addrStr = new ObservableField<>("");


    public ObservableField<String> gotoNum = new ObservableField<>("");
    public ObservableField<Float> rat = new ObservableField<Float>();
    public ObservableField<String> rank = new ObservableField<String>();


    public UserAddrDetailVM(@NonNull Application application, DataRepository repository) {
        super(application, repository);


    }

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    public class UIChangeObservable {
        //密码开关观察者
        public SingleLiveEvent<Integer> pSwitchEvent = new SingleLiveEvent<>();
        public SingleLiveEvent<Integer> refreshEvent = new SingleLiveEvent<>();
        public SingleLiveEvent<ResAddrDetail> updateUI = new SingleLiveEvent<>();

        public SingleLiveEvent<Integer> updateUICloectionStatus = new SingleLiveEvent<>();
        public SingleLiveEvent<String> startChat = new SingleLiveEvent<>();

    }




    //条目的点击事件
    public BindingCommand seatchCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startContainerActivity(SearchFragment.class.getCanonicalName());
        }
    });


    //给RecyclerView添加ObservableList
    public ObservableList<MultiItemViewModel> observableList = new ObservableArrayList<>();
    //RecyclerView多布局添加ItemBinding
    public ItemBinding<MultiItemViewModel> itemBinding = ItemBinding.of(new OnItemBind<MultiItemViewModel>() {
        @Override
        public void onItemBind(ItemBinding itemBinding, int position, MultiItemViewModel item) {
            //通过item的类型, 动态设置Item加载的布局
            String itemType = (String) item.getItemType();

            itemBinding.set(BR.viewModel, R.layout.discover_addr_detail_item_layout);

        }
    });




    public void getLoadInitData(String id,int sex){
        this.id = id ;
        //uc.pSwitchEvent.setValue();
        model.getApi().myUseraAddrDetail(id,sex,Config.PAGELIMT,page)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                //   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        uc.pSwitchEvent.setValue(1);
                        //      showDialog();
                        // dialog.show();
                    }
                })
                .subscribe(new BaseSubscriber<BaseRep<ResAddrDetail>>() {
                    @Override
                    public void onNext(BaseRep<ResAddrDetail> baseRep) {
                        if (baseRep.isOk()){
                            uc.pSwitchEvent.setValue(0);
                            status = baseRep.getData().getStatus();
                            if (baseRep.getData().getAddrInfo()!=null){
                                SearchAddrs addrs = baseRep.getData().getAddrInfo();
                                dataAddr = addrs;
                                KLog.d("html addrs ");
                                if (addrs==null){
                                    return;
                                }
                                uc.updateUI.setValue(baseRep.getData());
                                updateHeadViewInfo(addrs);
                            }

                            observableList.clear();
                            if (baseRep.getData().getGoWhere()!=null) {
                                for (GoToWhereNumberItem item : baseRep.getData().getGoWhere()) {
                                    AddrDetailItemVM items = new AddrDetailItemVM(UserAddrDetailVM.this, item);
                                    observableList.add(items);
                                }
                            }
                        }else {
                            uc.pSwitchEvent.setValue(2);
                            // RxToast.showToastShort(baseRep.getMsg());
//
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        //  dismissDialog();
                        uc.pSwitchEvent.setValue(2);
                        e.printStackTrace();
                        RxToast.showToastShort("网络出现故障");
                    }

                    @Override
                    public void onComplete() {
                        //   dismissDialog();
                    }

                });

    }

    private SearchAddrs dataAddr;

    public void getLoadData(int i,String id,int sex){
        //uc.pSwitchEvent.setValue();
        if (i == 0){
            page = 0;
        }
        page++;
        model.getApi().myUseraAddrDetail(id,sex,Config.PAGELIMT,page)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                //   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        uc.refreshEvent.setValue(1);
                        //      showDialog();
                        // dialog.show();
                    }
                })
                .subscribe(new BaseSubscriber<BaseRep<ResAddrDetail>>() {
                    @Override
                    public void onNext(BaseRep<ResAddrDetail> baseRep) {

                        super.onNext(baseRep);
                        uc.refreshEvent.setValue(0);
                        if (baseRep.isOk()){
                            if (i==0){
                                observableList.clear();
                            }
                            uc.updateUI.setValue(baseRep.getData());
                            if (baseRep.getData().getGoWhere()!=null) {
                                for (GoToWhereNumberItem item : baseRep.getData().getGoWhere()) {
                                    AddrDetailItemVM items = new AddrDetailItemVM(UserAddrDetailVM.this, item);
                                    observableList.add(items);
                                }
                            }

                        }else {
                            uc.refreshEvent.setValue(2);
                            // RxToast.showToastShort(baseRep.getMsg());
//
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        //  dismissDialog();
                        uc.refreshEvent.setValue(2);
                        e.printStackTrace();
                        RxToast.showToastShort("网络出现故障");
                    }

                    @Override
                    public void onComplete() {
                        //   dismissDialog();
                    }

                });
    }

    public void updateHeadViewInfo(SearchAddrs addrs){
        if (addrs==null){
            return;
        }
        KLog.d("html adasd ");
       // if (addrs.getPhotos()!=null && addrs.getPhotos().size()>=1){
            imgUrl.set(addrs.getPhoto());
     //   }

        name.set(addrs.getName());
        rat.set(addrs.getRating());
      //  gotoNum.set(addrs.get.getNum()+"人想去");


        if (addrs.getCost() == 0 ){
            rank.set("");
        }else {
            rank.set("¥"+addrs.getCost()+"/人");
        }
        String type=addrs.getCategory();
        addr.set(addrs.getDistance()+"km，"+type+"，"+addrs.getCity()+addrs.getArea());
        addrStr.set(addrs.getAddress());

       // addr.set(addrs.getDistance()+"km,"+type+","+addrs.getCity()+addrs.getArea());

      //  addrStr.set(addrs.getAddress());

    }



    public void addCloection(String id){
        //uc.pSwitchEvent.setValue();
        model.getApi().detailAddCloection(id)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                //   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                     //   uc.pSwitchEvent.setValue(1);
                              showDialog();
                        // dialog.show();
                    }
                })
                .subscribe(new BaseSubscriber<BaseRep>() {
                    @Override
                    public void onNext(BaseRep baseRep) {

                        super.onNext(baseRep);
                        dismissDialog();
                        if (baseRep.isOk()){
                            status = 1;
                            uc.updateUICloectionStatus.setValue(1);
                        }else {
                            RxToast.showToastShort(baseRep.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                          dismissDialog();
                     //   uc.pSwitchEvent.setValue(2);
                        e.printStackTrace();
                        RxToast.showToastShort("网络出现故障");
                    }

                    @Override
                    public void onComplete() {
                        //   dismissDialog();
                    }

                });

    }
    public void removeCloection(String id){
        //uc.pSwitchEvent.setValue();
        model.getApi().detailRemoveCloection(id)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                //   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                      //  uc.pSwitchEvent.setValue(1);
                        showDialog();
                        // dialog.show();
                    }
                })
                .subscribe(new BaseSubscriber<BaseRep>() {
                    @Override
                    public void onNext(BaseRep baseRep) {

                        super.onNext(baseRep);
                        dismissDialog();
                        if (baseRep.isOk()){
                            status = 0;
                            uc.updateUICloectionStatus.setValue(0);
                        }else {
                            RxToast.showToastShort(baseRep.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissDialog();
                        //   uc.pSwitchEvent.setValue(2);
                        e.printStackTrace();
                        RxToast.showToastShort("网络出现故障");
                    }

                    @Override
                    public void onComplete() {
                        //   dismissDialog();
                    }

                });

    }


    //条目的点击事件
    public BindingCommand itemClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            if(status == 0 ){

                addCloection(id);
            }else {
                removeCloection(id);
            }
            // viewModel.startContainerActivity(AddrDetailFragment.class.getCanonicalName());
            //     ToastUtils.showShort("我是头布局");
        }
    });




    public void yaoqing(String  uid,AddrDetailItemVM vm){
        //uc.pSwitchEvent.setValue();
        model.getApi().invitingHe(id,uid)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                //   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        //   uc.pSwitchEvent.setValue(1);
                        showDialog();
                        // dialog.show();
                    }
                })
                .subscribe(new BaseSubscriber<BaseRep>() {
                    @Override
                    public void onNext(BaseRep baseRep) {

                        super.onNext(baseRep);
                        dismissDialog();
                        if (baseRep.isOk()){
                            vm.yqBtnVisibility.set(View.GONE);
                            vm.yqnBtnVisibility.set(View.GONE);

                            vm.yyqBtnVisibility.set(View.VISIBLE);
                        }else {
                            RxToast.showToastShort(baseRep.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissDialog();
                        //   uc.pSwitchEvent.setValue(2);
                        e.printStackTrace();
                        RxToast.showToastShort("网络出现故障");
                    }

                    @Override
                    public void onComplete() {
                        //   dismissDialog();
                    }

                });

    }


    public void jieshouyaoqing(String ids,AddrDetailItemVM vm){
        //uc.pSwitchEvent.setValue();
        model.getApi().acceptInvite(ids)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                //   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        //   uc.pSwitchEvent.setValue(1);
                        showDialog();
                        // dialog.show();
                    }
                })
                .subscribe(new BaseSubscriber<BaseRep<ResMatch>>() {
                    @Override
                    public void onNext(BaseRep<ResMatch> baseRep) {

                        super.onNext(baseRep);
                        dismissDialog();
                        if (baseRep.isOk()){
                            vm.jsyqBtnVisibility.set(View.GONE);
                            vm.ypdBtnVisibility.set(View.VISIBLE);
                            Bundle bd= new Bundle();
                            bd.putString("data", GsonUtil.toJson(baseRep.getData()));
                            startContainerActivity(MatchFragment.class.getCanonicalName(),bd);

                        }else {
                            RxToast.showToastShort(baseRep.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissDialog();
                        //   uc.pSwitchEvent.setValue(2);
                        e.printStackTrace();
                        RxToast.showToastShort("网络出现故障");
                    }

                    @Override
                    public void onComplete() {
                        //   dismissDialog();
                    }

                });

    }
    public void startChat(String id){
        //uc.pSwitchEvent.setValue();
       uc.startChat.setValue(id);

    }


    //条目的点击事件
    public BindingCommand daohangClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            if (dataAddr!=null){

                try {
                    if (checkMapAppsIsExist(AppManager.getAppManager().currentActivity(),"com.autonavi.minimap")){
                        Intent intent_gdmap = new Intent();
                        intent_gdmap.setAction("android.intent.action.VIEW");
                        intent_gdmap.setPackage("com.autonavi.minimap");
                        intent_gdmap.addCategory("android.intent.category.DEFAULT");
                        intent_gdmap.setData(Uri.parse("androidamap://viewMap?sourceApplication=testDemo&lat=" + dataAddr.getLatitude() + "&lon=" + dataAddr.getLongitude() + "&dev=0"));
                        AppManager.getAppManager().currentActivity().startActivity(intent_gdmap);
                    }
                    else if (checkMapAppsIsExist(AppManager.getAppManager().currentActivity(),"com.baidu.BaiduMap")){

                        Intent intent_baidumap = new Intent();
                        intent_baidumap.setData(Uri.parse("baidumap://map/marker?location=" + dataAddr.getLatitude() + "," + dataAddr.getLongitude()+ "&traffic=on&src=andr.baidu.openAPIdemo"));
                        AppManager.getAppManager().currentActivity().startActivity(intent_baidumap);

                    }
                    else if (checkMapAppsIsExist(AppManager.getAppManager().currentActivity(),"com.autonavi.minimap")){

                        Intent intent_txmap = new Intent();
                        intent_txmap.setData(Uri.parse("qqmap://map/marker?marker=coord:"+dataAddr.getLatitude()+","+dataAddr.getLongitude()+";title:"+dataAddr.getName()+";addr:&referer=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"));
                        AppManager.getAppManager().currentActivity().startActivity(intent_txmap);
                    }else if(checkMapAppsIsExist(AppManager.getAppManager().currentActivity(),"com.google.android.apps.maps")){
                        Uri gmmIntentUri = Uri.parse("google.navigation:q=" + dataAddr.getLatitude() + "," + dataAddr.getLongitude());
                        Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
                        mapIntent.setPackage("com.google.android.apps.maps");
                        AppManager.getAppManager().currentActivity().startActivity(mapIntent);
                    }
                    else {
                        RxToast.showToastShort("未安装地图软件");
                    }
                }catch (Exception e){
                    RxToast.showToastShort("打开地图失败");
                }

            }
            // viewModel.startContainerActivity(AddrDetailFragment.class.getCanonicalName());
            //     ToastUtils.showShort("我是头布局");
        }
    });

    /**
     * 检测地图应用是否安装
     *
     * @param context
     * @param packagename
     * @return
     */
    public static boolean checkMapAppsIsExist(Context context, String packagename) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packagename, 0);
        } catch (Exception e) {
            packageInfo = null;
            e.printStackTrace();
        }
        if (packageInfo == null) {
            return false;
        } else {
            return true;
        }
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
